package com.example.yxwheather

import android.util.SparseArray
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.example.yxwheather.ui.home.HomeFragment
import com.example.yxwheather.ui.me.MeFragment
import com.example.yxwheather.ui.start.StartListFragment


class ViewPagerAdapter(fragmentActivity: FragmentActivity)
    : FragmentStateAdapter(fragmentActivity)  {
    override fun getItemCount(): Int {
        return 3
    }
    private val fragmentCache = SparseArray<Fragment>()
    override fun createFragment(position: Int): Fragment {
        val newFragment = fragmentCache.get(position)
        return if (newFragment != null) {
            newFragment
        } else {
            when (position) {
                0 -> HomeFragment()
                1 -> StartListFragment()
                2 -> MeFragment()
                else ->throw IllegalArgumentException("Invalid position: $position") //
            }
        }
        fragmentCache.put(position, newFragment)
        return newFragment
    }

}